package com.my.util;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.util.Map;

public class ElasticSearchUtil {

    /**
     * 查询指定索引、指定type、 指定id的文档记录
     * @param client
     * @param index
     * @param type
     * @param id
     * @return
     */
    public static String getDocument(TransportClient client, String index, String type, String id){

        String result = null;
        GetResponse getResponse = client.prepareGet(index, type, id).get();
        Map<String, Object> res = getResponse.getSourceAsMap();
        result = JSON.toJSONString(res);
        System.out.println("ElasticSearchUtil getDocument=================" + res.toString());

        return result;
    }

    public static IndexResponse insertDocument(TransportClient client, String index, String type, String id, String data, XContentType contentType){

        if(contentType == null){
            contentType = XContentType.JSON;
        }
        IndexResponse response = null;
        if(id == null){
            response = client.prepareIndex(index, type)
                    .setSource(data,  contentType)
                    .get();
        }
        response = client.prepareIndex(index, type, index)
                .setSource(data,  contentType)
                .get();
        if(response != null){
            System.out.println(response.toString());
            System.out.println("status: " + response.status());
        }
        return response;
    }
}
